import { apiUr } from './api';
import * as dayjs  from "@/tmui/tool/dayjs/esm/index";
import isoWeek from "@/tmui/tool/dayjs/esm/plugin/isoWeek/index"
const Dayjs = dayjs.default;
Dayjs.extend(isoWeek)

/**
 * 获取当前时间
 * @param day 'day'|'month'|'week'
 */
export function getNowDate(day:'day'|'month'|'week'):Array<string>{
    let d = Dayjs()
    if(day=='month') {
        return [d.startOf('month').format('YYYY/MM/DD'),d.endOf('month').format('YYYY/MM/DD')]
    }
    if(day=='week') {
        const startOfWeek = d.startOf('isoWeek').add(1, 'day').format('YYYY/MM/DD');
        const endOfWeek = d.endOf('isoWeek').add(1, 'day').format('YYYY/MM/DD');
        return [startOfWeek, endOfWeek];
    }
    return [d.format('YYYY/MM/DD'),d.format('YYYY/MM/DD')]
}
export function formatTimeBystr(day:string | number | Date | null | undefined,fsf = 'YYYY-MM-DD'):string{
    let d = Dayjs(day||new Date())
    return d.format(fsf)
}

/**
 * 时间处理成刚刚，等等
 * @param time 时间
 * @returns 值
 * 如果时间显示在10分钟内就显示：刚刚；如果时间在本日内就显示：时：分；如果时间在昨天就显示：昨天 时：分；如果时间过了昨天就显示星期几 时-分（星期是从周一开始）；如果时间超过了一周以上就显示：年月日 时：分
 */
export function formatTime(time: string | number | Date | null | undefined): string {
    if (!time) return ""
    const now = new Date();
    const target = typeof time === 'string' || typeof time === 'number' ? new Date(time) : time;

    const diff = now.getTime() - target.getTime();
    const diffMinutes = Math.floor(diff / (1000 * 60));
    const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));
	
    if (diffMinutes < 5) {
        return '刚刚'
    }
    else if (diffMinutes < 20) {
        return `${target.getHours()}:${target.getMinutes()}`;
    } else if (diffDays === 0) {
        return `${target.getHours()}:${target.getMinutes()}`;
    } else if (diffDays === 1) {
        return `昨天 ${target.getHours()}:${target.getMinutes()}`;
    } else if (diffDays < 7) {
        const weekday = target.getDay() === 0 ? 7 : target.getDay();
        let zc = {
            "1": "一",
            "2": "二",
            "3": "三",
            "4": "四",
            "5": "五",
            "6": "六",
            "7": "日",
        }
        // @ts-ignore
        return `星期${zc[weekday]} ${target.getHours()}:${target.getMinutes()}`;
    } else {
        const year = target.getFullYear();
        const month = target.getMonth() + 1;
        const day = target.getDate();
        return `${year}-${month}-${day} ${target.getHours()}:${target.getMinutes()}`;
    }
}


/**
 * 更新APP应用
 */
export function updateApp(){
    const updateManager = uni.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        // console.log(res.hasUpdate);
    });
    updateManager.onUpdateReady(function (res) {
        uni.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success(res) {
                if (res.confirm) {
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                    updateManager.applyUpdate();
                }
            }
        });

    });

    updateManager.onUpdateFailed(function (res) {
        // 新的版本下载失败
        uni.showModal({
            title: '失败',
            content: '版本下载失败了哦~',
            confirmText:"重试",
            cancelText:"取消",
            success(res) {
                if (res.confirm) {
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                    updateManager.applyUpdate();
                }
            }
        });
    });
}
/**
 * 请求自动登录
 */
export function wxlogin(){
    return new Promise((resolve,reject)=>{
        uni.login({
            provider:'weixin',
            fail(error){
                uni.showToast({title:'登录出错',icon:'error'})
                reject(error)
            },
            success(result) {
                const code = result.code;
                apiUr.wxlogin(code).then(r=>{
                    resolve(r.data)
                }).catch(error=>{
                    reject(error)
                })
            },
        })
    })
}



/**上传的文件对象和服务文件对象互转 */
export function fileToFuwuqiObj(files: any[]): any[] {
    const file = uni.$tm.u.deepClone(files)
    let su = file.filter(el => el.statusCode == 3);
    let successFiles: any[] = su.map(el => {
        let jsonData = JSON.parse(el.response);
        return jsonData.data;
    })
    return successFiles;
}
export function FuwuqiObjToFile(files:any[]): any[] {
    const file = uni.$tm.u.deepClone(files)
    let successFiles: any[] = file.map(el => {
        return {
            status: "上传成功",
            statusCode: 3,
            progress: 100,
            url: el.url,
            name: "",
            response: JSON.stringify({
                code: 0,
                msg: "上传成功",
                data: el
            })
        }
    })

    return successFiles;
}


